/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {Alert, DeviceEventEmitter, Dimensions, StyleSheet, Text, View} from 'react-native';
import QRCode from 'react-native-qrcode-svg';
import BluetoothSerial from 'react-native-bluetooth-serial';
import Qs from 'qs';
import axiosInstance from './utils/request';

const {ESC} = BluetoothSerial;

const WIN_WIDTH = Dimensions.get('window').width;
const WIN_HEIGHT = Dimensions.get('window').height;

export default class WxPayScene extends Component {

	constructor(props){
		super(props);
		const { params } = this.props.route;
		this.props.navigation.setOptions({
			title:'用户扫码支付'
		})
		this.state = {
			tips:'',
			outTradeNo:'1',
			payfee:params.payfee,
			qrCodeUrl:'二维码生成失败,请重试',
		}
  	}

  	//组件挂载完成后执行的方法
  	componentDidMount(){
		let params = this.props.route;
		this.fetchData(params.params);

		this.timer = setInterval(
		  () => {
			let data={
				outTradeNo:this.state.outTradeNo
			};
			this.fetchPayStatus(data);
		  },2000
		);
  	}

  	componentWillUnmount() {
    	// 如果存在this.timer，则使用clearTimeout清空。
    	// 如果你使用多个timer，那么用多个变量，或者用个数组来保存引用，然后逐个clear
		this.stopTimer();
  	}

	stopTimer(){
		this.timer && clearInterval(this.timer);
		console.log('clearTimeout>>>>>>>>>>>>');
	}

  	fetchPayStatus(data){
		let url=global.server.url+'/wxPay/payStatus';
		axiosInstance({
			method: 'post',
		  	url: url,
		  	data: Qs.stringify(data)
		})
        .then(res => {
			let data=res;
			if(data.status==0){
				this.setState({
					tips:'支付成功！',
				});
				this.stopTimer();
				this.printTips();
			}else if(data.status=='200'){
				this.setState({
					tips:'待支付完成后再离开本页面！',
				});
			}
        })
        .catch(err => {
        	console.log('fetchPayStatus网络异常！'+err);
        })
	}

    fetchData(data){
		//let url='http://192.168.0.103:8080/wxPay/getQrCodeUrl';
		let url=global.server.url+'/wxPay/payUrl';
		axiosInstance({
			method: 'post',
		  	url: url,
		  	data: data
		})
        .then(res => {
			this.setState({
				outTradeNo:res.outTradeNo,
				qrCodeUrl: res.qrCodeUrl
	   		});
        }).catch(err => {
        	console.log('fetchData时网络异常！'+err);
        })
	}

	printTips(){
		Alert.alert(
			'提示', //提示标题
			'支付成功，是否打印票据？', //提示内容
			[
				{
					text: '确定',
					onPress: ()=> {
						this.goBack();
						this.stopTimer();
					}
				},
				{
					text: '取消',
					onPress: () =>{
						this.stopTimer();
					}
				}
			]
		)
	}

	goBack(){
		DeviceEventEmitter.emit('print', {payMode:'54'});
		this.props.navigation.navigate('PayScene',{payMode:'54'})
	}

   setValue(text) {
	   this.setState({
			value: text
	   });
	}

    render() {
		let base64Logo = '..';
        return (
			<View style={styles.container}>
				 <View style={{height:WIN_HEIGHT,width:WIN_WIDTH,backgroundColor:'#E6E6FA',alignItems:'center',justifyContent:'center'}}>
				 	<Text style={{fontSize:18,marginBottom:20,fontWeight:"bold"}}>支付金额:{this.state.payfee}元</Text>
				 	<QRCode
						value={this.state.qrCodeUrl} // 生成二维码的value
						size={150}  // 二维码大小
						color="#333"  // 二维码主色
						backgroundColor="white"   // 二维码背景色
						//logo={{uri: base64Logo}}   // 二维码中间加载显示的logo,但是在android9.0及以上版本会报错，所以此处注释掉了。
						logoSize={30}             // 二维码logo大小
						logoBackgroundColor='transparent'  // 二维码logo背景色
					 />
                    <Text style={styles.headerText}>{this.state.tips}</Text>
                </View>
			</View>
		)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
		flexDirection: 'column',
        backgroundColor: 'white'
    },
	headerText:{
        fontSize:18,
		color:"#ff0000",
		marginTop:20,
    },
});
